package com.lcq.study.normal;

import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName QueueTest
 * @Description
 * @Author lichuanqi
 * @Date 2022/6/22 11:31
 * @Version 1.0
 **/
public class SynchronousQueueTest {

    private SynchronousQueue<Integer> queue;
    public static void main(String[] args) throws InterruptedException {
        SynchronousQueueTest queueTest = new SynchronousQueueTest();
        queueTest.start();
    }

    public void start() throws InterruptedException {
        queue = new SynchronousQueue<>();
        Thread producer = new Thread(new Producer());
        Thread consumer = new Thread(new Consumer());
        consumer.start();
        producer.start();

        producer.join();
        consumer.join();
    }


    class Producer implements Runnable{

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("add item:" + i);
                queue.add(i);
            }
        }
    }

    class Consumer implements Runnable{
        @Override
        public void run() {
            System.out.println("get queue====");
            try {
                while (true){
                    Integer num = queue.poll(10, TimeUnit.SECONDS);
                    System.out.println("get num: "+num);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
